package com.isoft.service.impl;

import com.isoft.entity.DfmePokeEntity;
import com.isoft.mapper.DfmePokeMapper;
import com.isoft.service.DfmePokeService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class DfmePokeServiceImpl implements DfmePokeService {
    private static final Logger logger = LoggerFactory.getLogger(DfmePokeServiceImpl.class);

    // 有效的STATUS值列表
    private static final List<String> VALID_STATUS = Arrays.asList(
            "NORMAL", "DELAYED", "CANCELLED", "BOARDING",
            "DEPARTED", "ALTERNATE", "RETURNED", "BOARDING_COMPLETED"
    );

    // 状态映射表：将XML中的状态映射到数据库中的有效状态
    private static final Map<String, String> STATUS_MAPPING = new HashMap<>();
    static {
        STATUS_MAPPING.put("POK", "NORMAL");  // 将POK映射为NORMAL
        STATUS_MAPPING.put("正常", "NORMAL");
        STATUS_MAPPING.put("延误", "DELAYED");
        STATUS_MAPPING.put("取消", "CANCELLED");
        STATUS_MAPPING.put("登机", "BOARDING");
        STATUS_MAPPING.put("起飞", "DEPARTED");
        // 可以根据需要添加更多映射
    }

    @Autowired
    private DfmePokeMapper dfmePokeMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-POKE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmePokeEntity entity) {
        // 映射STATUS值
        if (entity.getDflt() != null && entity.getDflt().getStatus() != null) {
            String status = entity.getDflt().getStatus();
            if (!VALID_STATUS.contains(status)) {
                // 尝试从映射表中获取对应的有效状态
                String mappedStatus = STATUS_MAPPING.getOrDefault(status, "NORMAL");
                logger.warn("Mapping invalid STATUS value: {} -> {}", status, mappedStatus);
                entity.getDflt().setStatus(mappedStatus);
            }
        }

        // 处理航班数据
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmePokeEntity entity = xmlParserUtil.parseXml(xmlContent, DfmePokeEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFME-POKE XML structure");
            }

            // 映射STATUS值
            if (entity.getDflt().getStatus() != null && !VALID_STATUS.contains(entity.getDflt().getStatus())) {
                String status = entity.getDflt().getStatus();
                String mappedStatus = STATUS_MAPPING.getOrDefault(status, "NORMAL");
                logger.warn("Mapping invalid STATUS value: {} -> {}", status, mappedStatus);
                entity.getDflt().setStatus(mappedStatus);
            }

            processFlightData(entity);

            return "DFME-POKE data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-POKE XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-POKE XML: " + e.getMessage());
        }
    }

    private void processFlightData(DfmePokeEntity entity) {
        // 插入元数据
        dfmePokeMapper.insertMeta(entity);

        // 插入航班基础信息，存在则跳过
        if (dfmePokeMapper.existsFlightBase(entity.getDflt()) == 0) {
            dfmePokeMapper.insertFlightBase(entity);
        } else {
            logger.info("Flight base already exists for FLIGHT_FILE_ID: {}，skip insert.", entity.getDflt().getFlightFileId());
        }
    }
}